<template>
	<div>
		<!-- <el-table ref="table" class="custom-table" border fit style="width: 100%" :data="tableData" :class="'normal-talbe'" :column-height="40" row-key="id"> -->
		<!-- <el-table-column v-for="(one) in fields" :key="one" min-width="160" :label="fieldsMap[one]" :fixed="one === 'oper' ? 'right' : null">
			<template slot-scope="{ row }">
        <template v-if="one === 'province' || one === 'city' || one === 'area'">{{ areaMap[row[one]] }}</template>
        <template v-else>{{ row[one] }}</template>
        <template v-if="one === 'oper'">
					<span @click.stop="del(row.id)" class="oprate delete">删除</span>
				</template>
			</template>
		</el-table-column> -->
	<!-- </el-table> -->
    <customerTableDetail
      @del="del"
      :headers="fields"
      :checkHeaders="fields"
      :fieldsMap="fieldsMap"
      :data="tableData"
      :headersConfig="false"
      :showPagination="false"
      :dynamic="true"
      :selection="false"
      :afterSales="true"
    ></customerTableDetail>
		<div class="top">
      <el-button type="text" size="small" :disabled="disabled" @click.stop="addCustomer" v-if="!tableData.length">添加客户</el-button>
		</div>
    <drawer
        class="customer"
        irection="rtl"
        :append-to-body="true"
        size="600px"
        title="添加客户"
        :drawer="isShow"
        @save="saveConfirm"
        @cancelFun="cancelFun"
        @closeDraw="cancelFun"
      >
        <template slot="column">
          <addCustomer ref="addCustomer" :areaMap="areaMap" :areaList="areaList" @addCustSuccess="addCustSuccess"></addCustomer>
        </template>
      </drawer>
	</div>
</template>

<script lang="ts">
import { Component, Mixins, Ref, Inject, Watch } from 'vue-property-decorator';
import widgetCommon from '../common/widgetCommon';
import drawer from '@/common/views/drawer/index.vue'
import customerTableDetail from '@/views/newCustomer/components/customerTableDetail.vue'
import addCustomer from '@/afterSales/views/business/components/addCustomer.vue'
import { busConfigStore } from '../../../../store/busConfigStore'
import { commonAction } from '@/utils/common'
import { fieldsMap } from './config'
import { CommonModule } from '@/store/modules/common'

@Component({
  name: 'associateUser',
  components: {
    addCustomer,
    drawer,
    customerTableDetail
  },
  filters: {
  },
  directives: {
  }
})
export default class extends Mixins(widgetCommon) {
  [x: string]: any;
  private isShow = false
  private areaList: any = []
  private popperElm: any
  private isNotFetch = true
  private inputVal = '';
  @Inject({ default: {} }) public readonly recordVM!: any;
  @Ref() public formRef!: any;
  private fieldsMap = {}
  private allServiceItemObj = {}
  private visible = false
  private customerMsg = {} as any
  private list = []
  private get areaMap () {
    const labels = {}
    const handleFn = (list) => {
      list.map(item => {
        labels[item.id] = item.fullname
        if (item.children) {
          handleFn(item.children)
        }
      })
    }
    if (this.areaList && this.areaList.length) {
      handleFn(this.areaList)
    }
    return labels
  }

  private saveConfirm () {
    (this.$refs as any).addCustomer.submit()
  }

  private addCustomer () {
    this.isShow = true
    this.$nextTick(() => {
      (this.$refs as any).addCustomer.clearForm()
    })
  }

  private addCustSuccess (data: any) {
    this.isShow = false
    this.isNotFetch = false
    const { customId, customAddressId, customContactId } = data
    this.value = {
      customId,
      customAddressId,
      customContactId
    }
    this.customerMsg = data
    this.tableChangeValue()
  }

  private cancelFun () {
    this.isShow = false
  }

  private rowClick (data: any) {
    const row = {
      id: data.id,
      count: 0
    }
    console.log(row)
    if (this.value) {
      this.value.push(row)
    } else {
      this.value = [row]
      // this.$set(this, 'value', [row])
    }
    this.tableChangeValue()
  }

  private get fields () {
    this.fieldsMap = Object.assign({}, fieldsMap, busConfigStore.customerFieldsMap)
    if (!this.isConfig && !this.disabled) {
      return [...this.item.displayField, ...['oprate']]
    } else {
      return this.item.displayField
    }
  }

  private del (id: string) {
    this.value.customId = 'empty'
    this.customerMsg = {}
    this.tableChangeValue()
  }

  private get dataFilter () {
    if (!this.inputVal) {
      return this.list;
    }
    return this.list.filter((item: any) => {
      return item.name.includes(this.inputVal);
    });
  }

  private get tableData () {
    if (this.customerMsg._id) {
      return [this.customerMsg]
    }
    return [];
  }

  public foucs () {
    this.visible = true;
  }

  public hideOnly () {
    this.visible = false;
  }

  @Watch('value', { immediate: true })
  private valueInput (val: any) {
    if (val && this.isNotFetch) {
      this.getDetail(val)
    }
  }

  private getDetail (val) {
    console.log(this.value)
    if (val.customId !== 'empty') {
      commonAction({
        url: '/server-crm/action/customer/customerAndContactDetail',
        method: 'post',
        data: {
          addressId: val.customAddressId,
          contactorId: val.customContactId,
          customerId: val.customId
        }
      }).then(res => {
        if (res.success) {
          this.isNotFetch = true
          this.customerMsg = Object.assign({}, res.data.customer, res.data.address, res.data.contactor)
        }
      })
    }
  }

  private beforeMount () {
    this.$getCache('/base/action/general/cache/query', ['region'], false).then(res => {
      if ((CommonModule as any).publicCache.region?.result.length) {
        this.areaList = (CommonModule as any).publicCache.region.result
      }
    })
    this.$nextTick(() => {
      if (this.$refs.popover as any) {
        this.popperElm = (this.$refs.popover as any).$refs.popper
      }
    })
  }
}
</script>
<style lang="stylus">
.spare-popover
  width: 700px;
  max-height: 400px;
  overflow-y: auto;
</style>

<style lang="stylus" scoped>
.el-input--radius
  margin-bottom: 12px
.top {
	display flex
	justify-content space-between
	padding-bottom 8px
	line-height 34px
	.middle {
		line-height 33px
		flex 1
		display flex
		align-items center
		.middle-btn {
			margin-left 18px
		}
	}
	.right {
		flex-basis 250px
		text-align right
	}
}
</style>
